package com.tdwyz.fictionmanage.controller;

import com.tdwyz.fictionmanage.pojo.Fiction;
import com.tdwyz.fictionmanage.pojo.PageBean;
import com.tdwyz.fictionmanage.pojo.Result;
import com.tdwyz.fictionmanage.service.FictionService;
import com.tdwyz.fictionmanage.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("fiction")
public class FictionController {
    @Autowired
    private FictionService fictionService;

    @PostMapping
    public Result add(@RequestBody Fiction fiction){
        //文章的Service
        return Result.toAjax(fictionService.add(fiction));
    }


    @PutMapping
    public Result update(@RequestBody Fiction fiction){
        //1.存在性校验
        Fiction ficDb = fictionService.getById(fiction.getId());
        if(ficDb==null){
            return Result.defeat("小说不见了");
        }

        //3.判断文章是否归属当前用户
        int userId = ThreadLocalUtil.getUserId();
        if(userId != ficDb.getCreateUser()){
            return Result.defeat("修改失败");
        }
        return Result.toAjax(fictionService.update(fiction));
    }

    //获取我的小说列表
    @GetMapping("/my")
    public Result<PageBean<Fiction>> listMy(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) Integer categoryId
    ){
        PageBean<Fiction> pageBean = fictionService.listMy(pageNum,pageSize,categoryId);
        return Result.success(pageBean);
    }

    //获取所有小说列表
    @GetMapping
    public Result<PageBean<Fiction>> list(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) Integer categoryId
    ){
        PageBean<Fiction> pageBean = fictionService.list(pageNum,pageSize,categoryId);
        return Result.success(pageBean);
    }



    @GetMapping("detail")
    public Result<Fiction> detail(@RequestParam Integer id){
        return Result.success(fictionService.getById(id));
    }

    @DeleteMapping
    public Result delete(@RequestParam Integer id){
        //1.存在性校验
        Fiction ficDb = fictionService.getById(id);
        if(ficDb==null){
            return Result.defeat("小说不存在");
        }
        //2.归属问题
        int userId = ThreadLocalUtil.getUserId();
        if(userId != ficDb.getCreateUser()){
            return Result.defeat("删除失败，无法删除他人小说哦");
        }
        //3.删除
        return Result.toAjax(fictionService.delete(id));
    }
}
